//
//  SHOrdersListViewController.swift
//  ServiceHelper
//
//  Created by Xuedan on 15/12/12.
//  Copyright © 2015年 Stan Wu. All rights reserved.
//

import UIKit
import AVFoundation

class SHOrdersListViewController:UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,SHOrdersListDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,SHOrderNotificationDetailDelegate,SWImageViewDelegate,UIAlertViewDelegate,UITextFieldDelegate,SCanDelegate{

    
    var tvList: UITableView!
     var tvListClass: UITableView!
    var tvListPerson: UITableView!
    var lastIndexPath :  NSIndexPath!
    var lastIndex :  NSInteger!
    var vAllOrders: SHOrdersListView!
    //    var vSelectPerson :SHSelectTakeCarPersonVIew
    var vNotificationDetail: SHOrdersNotificationDetailView!
    var aryList = NSMutableArray()
    var aryClassList = NSMutableArray()
    var aryPersonList = NSMutableArray()
    var selectedOrder: NSDictionary?
    var dicSelectedPersonInfo: NSDictionary?
    var lblSelectedClass:UILabel!
    var dicOrderDetail: NSDictionary?
    var refreshController: UIRefreshControl!
    var dCurrentPage = 1
    lazy var searchBar :UISearchBar = UISearchBar(frame: CGRectMake(0, 0, 300,20))
    var order_status: String = "0"
    var notice_status: String = "0"
    var strDefaultClass: String = "所有类别"
    //    var strNavTitle = NSString()
    var realkey : NSString?
    var imgvPhoto :UIImageView!
    var pop: UIPopoverController!
    var vPay : UIView!
    var vMark : UIView!
    var vMarkTabBar : UIView!
    var vMarkSearch : UIView!
    var vMarkClass : UIView!
    var vMarkPerson:UIView!
    var vFooterPerson :UIView!
    var btnHide: UIButton!
    var btnResignSearchBar: UIButton!
    var btnHideClass:UIButton!
    var btnHiddenMarkTabbar:UIButton!
    var photoCount = Int()
    var aryPhotos = NSMutableArray()
    var aryPhotosURI = NSMutableArray()
    var tfPrice : UITextField!
    var isSelectedPerson: Bool!
  
    var isFromSearchOrder: Bool?
    var isFromWaitingOrder: Bool?
    var IndexSelected : NSNumber!
    var isSelectedNotice: Bool!
    var IndexNoticeSelected : NSNumber!
    var isStartLoadingMore: Bool?
    var vSearchOrderView : UIView!
    var btnShowSearch :UIButton!
    
    var btnHidePusPay :UIButton!
    var imgvSearchBG :UIImageView!
    var aryButtonStatus :NSMutableArray!
    
    var imagePicker:UIImagePickerController!
    var strPrice : NSString!
    var networkConnectFalse: Bool! = false
    var BoolGetMore: Bool! = false
    var BoolIsUsedOSS: Bool! = false
    
    var checkNo : NSString?
    
    var client : OSSClient!
   
    var strNavTitle: NSString?{
        didSet{
            
            //            strShowType = strType
        }
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        NSThread.detachNewThreadSelector(#selector(SHOrdersListViewController.loadData), toTarget: self, withObject: nil)
        NSThread.detachNewThreadSelector(#selector(SHOrdersListViewController.getWaitingOrdersCounts), toTarget: self, withObject: nil);
    }
   
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addBGColor()
        // Do any additional setup after loading the view.
        
        self.setNavBGImage()
        if BoolIsUsedOSS == true{
            self.initOSSCliect()
        }
        aryButtonStatus = [false ,false,false,false,false,false,false,false]
        //        aryButtonStatus = NSMutableArray.addObjectsFromArray(ary)
        aryClassList = ["所有类别","已发起","已确认","服务中","待付款","待评价","已评价","已取消","变更中"]
        lastIndex = 0
        lastIndexPath = NSIndexPath(forRow: 0, inSection: 0)
        isStartLoadingMore = false
        tvList = UITableView(frame: CGRectMake(0, 0, 370, 768-44-20-49))
        tvList.backgroundColor = UIColor.clearColor()
        tvList.delegate = self
        tvList.dataSource = self
        tvList.separatorStyle = .None
        self.view.addSubview(tvList)
        tvList.tableFooterView = UIView.init(frame: CGRectZero)
        
    
        
        var myDelegate:AppDelegate
        myDelegate = (UIApplication.sharedApplication().delegate as? AppDelegate)!
        vMarkClass = UIView.init(frame: CGRectMake(0,0,1024,768))
        vMarkClass .backgroundColor = UIColor.blackColor()
        vMarkClass.alpha = 0.5
        vMarkClass.hidden = true
        if #available(iOS 9.0, *) {
            //高于 iOS 8.0
            myDelegate.window?.addSubview(vMarkClass)
            
        } else {
            vMarkClass.frame = CGRectMake(0, 0, 1024, 668)
            //低于 iOS 8.0
            self.view.addSubview(vMarkClass)
            myDelegate.window?.addSubview(vMarkClass)
        }
        
        
        btnHideClass = UIButton (type: UIButtonType.Custom)
        btnHideClass.frame = CGRectMake(0, 0, 1024, 768)
        btnHideClass.backgroundColor = UIColor.clearColor()
        myDelegate.window?.addSubview(btnHideClass)
        btnHideClass.addTarget(self, action: #selector(SHOrdersListViewController.hideClassView), forControlEvents: .TouchUpInside)
        btnHideClass.hidden = true
        
        tvListClass = UITableView(frame: CGRectMake(0, 64+30, 320, 440))

        tvListClass.backgroundColor = UIColor.whiteColor()
        tvListClass.delegate = self
        tvListClass.dataSource = self
        tvListClass.separatorStyle = .SingleLine
        tvListClass.tableFooterView = UIView.init(frame: CGRectMake(0, 0, 0, 0))
        
        tvListClass.bounds.origin = self.view.bounds.origin
        if #available(iOS 8.0, *) {
            tvListClass.frame = CGRectMake(0, 64+30, 320, 440);
            //高于 iOS 8.0
            myDelegate.window?.addSubview(tvListClass)
            
        } else {
            tvListClass.frame.origin = CGPointMake(0, 30)
            //低于 iOS 8.0
            self.view.addSubview(tvListClass)

        }
        tvListClass.hidden = true
        
        if isFromWaitingOrder == true{
            order_status = "1,3,7,8,10,12,14,15,16"
        }else{
            order_status = "0"
            NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SHOrdersListViewController.networkStatusChanged(_:)), name: ReachabilityStatusChangedNotification, object: nil)
            Reach().monitorReachabilityChanges()
        }
        searchBar.placeholder = "搜索订单号"
        searchBar.delegate = self
        // 设置背景颜色
        searchBar.backgroundColor = UIColor.clearColor()
//        searchBar.backgroundColor = UIColor(patternImage: UIImage(named: "search_bar.png")!)
        
        let rightNavBarButton = UIBarButtonItem(customView: searchBar)
        
        let scanButton  = UIButton(frame:CGRectMake(0, 0, 75, 30))
        scanButton.setImage(UIImage(named: "sweep.png"), forState: .Normal)
        scanButton.addTarget(self,action:#selector(SHOrdersListViewController.scanButtonClicked),forControlEvents:.TouchUpInside)
        let rightNavBarButtonScan = UIBarButtonItem(customView: scanButton)
        
        let userName = SHDataProvider.getUserInfo()?.objectForKey("username") as! String
        let showManagerButton  = UIButton(frame:CGRectMake(0, 0, 140, 30))
//        showManagerButton.setImage(UIImage(named: "sweep.png"), forState: .Normal)
//        showManagerButton.addTarget(self,action:Selector("scanButtonClicked"),forControlEvents:.TouchUpInside)
        showManagerButton.setImage(UIImage(named: "manager.png"), forState: .Normal)
        showManagerButton.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0)
        showManagerButton.setTitle("管理员：\(userName)", forState: .Normal)
        showManagerButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        showManagerButton.titleLabel?.font = UIFont.systemFontOfSize(12)
        let rightNavBarButtonShow = UIBarButtonItem(customView: showManagerButton)
        
        
        //按钮间的空隙
        let gap = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil,
            action: nil)
        gap.width = 15;
        
        //用于消除右边边空隙，要不然按钮顶不到最边上
        let spacer = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil,
            action: nil)
        spacer.width = -10;
        
        //设置按钮（注意顺序）
        self.navigationItem.rightBarButtonItems = [spacer,rightNavBarButtonShow,gap,rightNavBarButtonScan,gap,rightNavBarButton]
        
//        self.navigationItem.rightBarButtonItem = rightNavBarButton
        
        self.createOrderDetailView()
    
        vMarkSearch = UIView.init(frame: CGRectMake(0, 0, 320, 768))
        vMarkSearch.backgroundColor = UIColor.blackColor()
        vMarkSearch.alpha = 0.30
        self.view.addSubview(vMarkSearch)
        vMarkSearch.hidden = true
        
        imgvSearchBG = UIImageView.init(frame: CGRectMake(0, 50, 320, 360))
        imgvSearchBG.image = UIImage(named: "bg")
        imgvSearchBG.userInteractionEnabled = true
        self.view.addSubview(imgvSearchBG)
        imgvSearchBG.hidden = true
        
        
        var titles = "预约成功，预约已确认，待上门取车，正在服务中，待送车上门，待支付，待评价，已完成".componentsSeparatedByString("，")
        for i in 0 ..< titles.count{
            let col = i % 2
            let row = i / 2
            
            let btn = UIButton(type: .Custom)
            btn.setBackgroundImage(UIImage(named: "nor"), forState: .Normal)
            btn.setBackgroundImage(UIImage(named: "sel"), forState: .Selected)
            btn.sizeToFit()
            btn.frame = CGRectMake(20 + (CGFloat)(150*col), 30 + (CGFloat)(62*row), 130, 40) //CGRectMake(CGFloat(20+130*col), CGFloat(20+62.5*row), 130 , 40)
            btn.setTitle(titles[i], forState: .Normal)
            btn.titleLabel?.font = UIFont.boldSystemFontOfSize(17)
            btn.setTitleColor(UIColor.grayColor(), forState: .Normal)
            btn.setTitleColor(UIColor.whiteColor(), forState: .Selected)
            
            btn.setImage(UIImage(named: "right_icon"), forState: .Selected)
            btn.titleEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0)
            btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -160)
            btn.tag = 300+i
            btn.hidden = true
            btn.addTarget(self, action: #selector(SHOrdersListViewController.searchClassedSelected(_:)), forControlEvents: .TouchUpInside)
            imgvSearchBG.addSubview(btn)
            
        }
        
        let btn = UIButton(type: .Custom)
        btn.setBackgroundImage(UIImage(named: "sel"), forState: .Normal)
//        btn.backgroundColor = ORANGECOLOR
        btn.sizeToFit()
        btn.frame = CGRectMake(55, 300, 210, 45)
        btn.setTitle("确定", forState: .Normal)
        btn.titleLabel?.font = UIFont.boldSystemFontOfSize(20)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.tag = 308
        btn.hidden = true
        btn.addTarget(self, action: #selector(SHOrdersListViewController.searchClassedSelected(_:)), forControlEvents: .TouchUpInside)
        imgvSearchBG.addSubview(btn)
        
        
        let line = UIView(frame: CGRectMake(0, 275, 320 , 0.5))
        line.backgroundColor = UIColor(white: 0.88, alpha: 1)
        imgvSearchBG.addSubview(line)
        
        
        
        vMarkPerson = UIView.init(frame: CGRectMake(0,0,1024,768))
        vMarkPerson.backgroundColor = UIColor.blackColor()
        vMarkPerson.alpha = 0.5
        myDelegate.window?.addSubview(vMarkPerson)
        vMarkPerson.hidden = true
        
        btnHide = UIButton (type: UIButtonType.Custom)
        btnHide.frame = CGRectMake(0, 0, 1024, 768)
        btnHide.backgroundColor = UIColor.clearColor()
        myDelegate.window?.addSubview(btnHide)
        btnHide.addTarget(self, action: #selector(SHOrdersListViewController.dismissShowViews), forControlEvents: .TouchUpInside)
        btnHide.hidden = true
        
        tvListPerson = UITableView(frame: CGRectMake(1024-270, 64, 270, 768-44-20-75))
        tvListPerson.backgroundColor = UIColor.whiteColor()
        tvListPerson.delegate = self
        tvListPerson.dataSource = self
        tvListPerson.separatorStyle = .None
        myDelegate.window?.addSubview(tvListPerson)
        tvListPerson.hidden = true

        vFooterPerson = UIView.init(frame: CGRectMake(1024-270, 768-75, 270, 75))
        vFooterPerson.backgroundColor = UIColor.whiteColor()
        vFooterPerson.layer.shadowColor = UIColor.blackColor().CGColor
        vFooterPerson.layer.shadowRadius = 1
        vFooterPerson.layer.shadowOffset = CGSizeMake(-2, 0)
        vFooterPerson.layer.shadowOpacity = 0.1
        myDelegate.window?.addSubview(vFooterPerson);
        vFooterPerson.hidden = true
//        tvListPerson.tableFooterView = vFooterPerson
        
        let btnSelectedPerson  = UIButton(type: UIButtonType.Custom)
        btnSelectedPerson.frame = CGRectMake(35, 15, 200, 45)
        btnSelectedPerson.backgroundColor = ORANGECOLOR
        btnSelectedPerson.setTitle("确定", forState: UIControlState.Normal)
        btnSelectedPerson.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        vFooterPerson.addSubview(btnSelectedPerson)
        btnSelectedPerson.addTarget(self, action: #selector(SHOrdersListViewController.btnSelectedPersonClicked), forControlEvents: .TouchUpInside)
        
        //        tvListPerson.tableFooterView = vFooterPerson
        
        
        btnResignSearchBar = UIButton(type: .Custom)
        btnResignSearchBar.backgroundColor = UIColor.clearColor()
        btnResignSearchBar.frame = CGRectMake(0, 0, 1024, 300)
        btnResignSearchBar.addTarget(self, action: #selector(SHOrdersListViewController.btnResignSearchBarClicked), forControlEvents: .TouchUpInside)
        self.view.addSubview(btnResignSearchBar)
        btnResignSearchBar.hidden = true
        
//        NSThread.detachNewThreadSelector("loadData", toTarget: self, withObject: nil)
        
        refreshController = UIRefreshControl()
        refreshController.addTarget(self, action: #selector(SHOrdersListViewController.refreshChanged(_:)), forControlEvents: .ValueChanged)
        tvList.addSubview(refreshController)
        
        //        self.hiddenTakeCarPerson()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SHOrdersListViewController.refresh), name: "RefreshOrderList", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SHOrdersListViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
        
    }
    func btnResignSearchBarClicked(){
        btnResignSearchBar.hidden = true
        searchBar.resignFirstResponder()
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func createNotificationDetailView(){
        vNotificationDetail = SHOrdersNotificationDetailView(frame: CGRectMake(320, 0, 1024-320, 768))
        vNotificationDetail.backgroundColor = UIColor.whiteColor()
        vNotificationDetail.strNew = strNavTitle
        vNotificationDetail.delegateNotification = self
        vNotificationDetail.strStatus = "1"
        self.view.addSubview(vNotificationDetail)
        //        vNotificationDetail.hidden = true
    }
    
    func createOrderDetailView(){
        vAllOrders = nil
        vAllOrders = SHOrdersListView(frame: CGRectMake(370, 0, 1024-370, 768-49))
        vAllOrders.backgroundColor = UIColor(red: 0.96, green: 0.96, blue: 0.97, alpha: 1)
        vAllOrders.strNew = strNavTitle
        vAllOrders.layer.shadowColor = UIColor.blackColor().CGColor
        vAllOrders.layer.shadowRadius = 1
        vAllOrders.layer.shadowOffset = CGSizeMake(-2, 0)
        vAllOrders.layer.shadowOpacity = 0.1
        vAllOrders.ordersListDelegate = self
        vAllOrders.strType = "1"
        self.view.addSubview(vAllOrders)
        //        vAllOrders.hidden = true
        
    }
    
    //扫描
    func scanButtonClicked(){
        
        //设置扫码区域参数
        var style = LBXScanViewStyle()
        style.centerUpOffset = 44;
        style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner;
        style.photoframeLineW = 2;
        style.photoframeAngleW = 18;
        style.photoframeAngleH = 18;
        style.isNeedShowRetangle = false;
        
        style.anmiationStyle = LBXScanViewAnimationStyle.LineMove;
        
        style.colorAngle = UIColor(red: 0.0/255, green: 200.0/255.0, blue: 20.0/255.0, alpha: 1.0)
        
        
        style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_Scan_weixin_Line")
        
        
        NSNotificationCenter.defaultCenter().postNotificationName("HiddenTabBar", object: nil)
        let vc = LBXScanViewController();
        vc.scanSuccesDelegate = self
        vc.scanStyle = style
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
       
//        self.sendLocalNotiction()
    }
    
    //本地推送
//    func sendLocalNotiction() {
//        //创建推送UILocalNotification
//        let localNotifiction = UILocalNotification()
//        //推送时间30s后
//        localNotifiction.fireDate = NSDate(timeIntervalSinceNow: 10)
//        //时区(本地)
//        localNotifiction.timeZone = NSTimeZone.systemTimeZone()
//        //推送消息
//        localNotifiction.alertBody = "本地推送消息\(NSDate())"
//        //角标设置
//        localNotifiction.applicationIconBadgeNumber = 1
//        if #available(iOS 8.2, *) {
//            localNotifiction.alertTitle = "本地推送测试"
//        } else {
//            // Fallback on earlier versions
//        }
//        //推送声音系统声音，也可以是bundle里面的音乐
//        localNotifiction.soundName = UILocalNotificationDefaultSoundName
//        //附加信息
//        localNotifiction.userInfo = ["name":"句芒"]
//        //添加推送
//        UIApplication.sharedApplication().scheduleLocalNotification(localNotifiction)
//        //取消推送
//        //UIApplication.sharedApplication().cancelLocalNotification(localNotifiction)
//    }
    
    func hideClassView(){
        tvListClass.hidden = true
        vMarkClass.hidden = true
        btnHideClass.hidden = true
    }

    
    func dismissShowViews(){
        self.view.endEditing(true)
        if tfPrice != nil{
            tfPrice.resignFirstResponder()
        }
       
        if vMarkTabBar != nil{
             vMarkTabBar.hidden = true
        }
        if btnHiddenMarkTabbar != nil{
            btnHiddenMarkTabbar.hidden = true
        }
        btnHide.hidden = true
        vMarkPerson.hidden = true
        tvListPerson.hidden = true
        vFooterPerson.hidden = true
        if vMark != nil {
            vMark.hidden = true
        }
        
        if btnHidePusPay != nil{
            btnHidePusPay.hidden = true
        }
        
        if vPay != nil {
            vPay.hidden = true
            
        }
        vAllOrders.btnReset.userInteractionEnabled = true
        self.aryPhotos.removeAllObjects()
        self.aryPhotosURI.removeAllObjects()
        photoCount = 0
    }
    
    func btnSelectedPersonClicked(){
        btnHide.hidden = true
        vMarkPerson.hidden = true
        tvListPerson.hidden = true
        vFooterPerson.hidden = true
        if dicSelectedPersonInfo != nil {
            let strOrderStatus = vAllOrders.OrdersInfo?.objectForKey("order_status")?.intValue
            _ = vAllOrders.OrdersInfo?.objectForKey("pick_type") as! String!
            
            if strOrderStatus == 3{
                NSThread.detachNewThreadSelector(#selector(SHOrdersListViewController.selectedGetCarPerson), toTarget: self, withObject: nil)
            }else  if strOrderStatus == 12 || strOrderStatus == 17{
//                if orderType == "2"{ //4
                    NSThread.detachNewThreadSelector(#selector(SHOrdersListViewController.selectedSendCarPerson), toTarget: self, withObject: nil)

            }else  if strOrderStatus == 1{
                NSThread.detachNewThreadSelector(#selector(SHOrdersListViewController.selectedGetCarPerson), toTarget: self, withObject: nil)
            }else  if strOrderStatus == 15{
                NSThread.detachNewThreadSelector(#selector(SHOrdersListViewController.selectedGetCarPerson), toTarget: self, withObject: nil)
            }
            
        }else{
            UIAlertView.show(nil, message: "请选择取送车服务人员", cancelButton: nil)
            vAllOrders.btnReset.userInteractionEnabled = true
        }
        
    }
    
    //选中搜索
    func searchClassedSelected (sender:UIButton){
        
        if sender.tag != 308{
            let isSel  = aryButtonStatus[sender.tag-300].boolValue
            if isSel == false{
                sender.selected = true
                aryButtonStatus[sender.tag-300] = true
            }else{
                sender.selected = false
                aryButtonStatus[sender.tag-300] = false
            }
            
        }
        
        
        switch sender.tag{
        case 300:
            print(300)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -165)
        case 301:
            print(301)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -185)
            
        case 302:
            print(302)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -185)
        case 303:
            print(303)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -185)
        case 304:
            print(304)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -185)
        case 305:
            print(305)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -150)
        case 306:
            print(306)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -150)
        case 307:
            print(307)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -150)
        case 308:
            print(308)
            vMarkSearch.hidden = true
            imgvSearchBG.hidden = true
            btnShowSearch.selected = false
            
            self.changeOrderStatus()
            
        default:()
            
        }
        
    }
    
    
    func changeOrderStatus(){
        let ary = ["1","3","6","8","11","4,9","10","5"]
        let str = NSMutableString()
        for i in 0 ..< aryButtonStatus.count{
            let sel = aryButtonStatus.objectAtIndex(i).boolValue
            if sel == true{
                str.appendString(ary[i])
                str.appendString(",")
            }
        }
        
        
        order_status = str as String
        self.refresh()
    }
    
    
    func refreshChanged(sender: UIRefreshControl){
        self.refresh()
    }
    
    func refresh(){
        NSThread.detachNewThreadSelector(#selector(SHOrdersListViewController.loadData), toTarget: self, withObject: nil)
    }
    
    func loadData(){
        autoreleasepool { () -> () in
            dCurrentPage = 1;
                
                let strSearchText :NSString = searchBar.text!
                if strSearchText.length <= 0 {
                    let dict = SHDataProvider.getDealerOrderList(["order_status":order_status,"dealer_id":SHDataProvider.getDealerID()])
                    
                    //            var dict = SHDataProvider.getDealerOrderList(["dealer_id":SHDataProvider.getDealerID()])
                    
                    let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let orderList = ary{
                            self.aryList.removeAllObjects()
                            self.aryList = NSMutableArray(array: orderList)
                            
                            if orderList.count>0{
                                let formatter = NSDateFormatter()
                                formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
                                let d = formatter.dateFromString(orderList[0].objectForKey("create_time") as! String)
                                if let dd = d{
                                    if self.order_status == "0" || self.order_status == "1"{
                                        NSUserDefaults.standardUserDefaults().setObject(dd, forKey: "LatestOrderTime")
                                    }
                                    
                                }
                            }
                        }else{
                            self.aryList.removeAllObjects()
                        }
                        
                        self.tvList.reloadData()
                        self.refreshController.endRefreshing()
                        
                        if self.aryList.count>0{
                            var number = 0
                            for i in 0 ..< self.aryList.count {
                                let info = self.aryList[i]
                                let checkstring = info.objectForKey("check_no") as? String
                                if self.checkNo?.isEqualToString(checkstring!) == true {
                                    number = i
                                    break
                                }
                            }
                            self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: number, inSection: 0))
                        }else{
                            self.vAllOrders.OrdersInfo = nil
                        }
                        
                        
                    })
                    
                }else{
                    let dict = SHDataProvider.getDealerOrderList(["search_no":searchBar.text!,"account_type":"1","order_status":order_status,"dealer_id":SHDataProvider.getDealerID()])
                    let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let orderList = ary{
                            self.aryList.removeAllObjects()
                            self.aryList = NSMutableArray(array: orderList)
                            
                            if orderList.count>0{
                                let formatter = NSDateFormatter()
                                formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
                                let d = formatter.dateFromString(orderList[0].objectForKey("create_time") as! String)
                                if let dd = d{
                                    if (self.order_status == "0" || self.order_status == "1") && strSearchText.length == 0{
                                        NSUserDefaults.standardUserDefaults().setObject(dd, forKey: "LatestOrderTime")
                                    }
                                }
                            }
                        }else{
                            self.aryList.removeAllObjects()
                        }
                        
                        self.tvList.reloadData()
                        self.refreshController.endRefreshing()
                        
                        if self.aryList.count>0{
                            self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))
                        }else{
                            self.vAllOrders.OrdersInfo = nil
                        }
                        
                        
                    })
                    
                }
            
        }
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        if aryList.count >= 20 * self.dCurrentPage {
            if aryList.count >= 20  * self.dCurrentPage{
                let cunt =  aryList.count
                if (scrollView.contentOffset.y + scrollView.frame.size.height) >  (CGFloat)( 150 * cunt)+100 {
                    let footview = UIView.init(frame: CGRectMake(0, 0, 370, 40))
                    footview.backgroundColor = UIColor(white: 0.9, alpha: 1)
                    
                    let activityIndicator = UIActivityIndicatorView.init()
                    activityIndicator.activityIndicatorViewStyle  = UIActivityIndicatorViewStyle.Gray
                    activityIndicator.center = CGPointMake(185, 20)
                    footview.addSubview(activityIndicator)
                    
                    activityIndicator.startAnimating()
                    tvList.tableFooterView = footview
                    
                    if isStartLoadingMore == false{
                        isStartLoadingMore = true
//                        NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: Selector("delayLoadMoreData"), object: nil)
                        self.performSelector(#selector(SHOrdersListViewController.loadMoreData), withObject: nil, afterDelay: 0.3)
                    }else{
                        return
                    }
                    
                }
            }
            
        }
        
    }
    
    func loadMoreData(){
        autoreleasepool { () -> () in

                let strSearchText :NSString = searchBar.text!
                if strSearchText.length <= 0 {
                    let dict = SHDataProvider.getDealerOrderList(["order_status": order_status,"dealer_id":SHDataProvider.getDealerID(),"page":"\(self.dCurrentPage+1)"])
                    
                    let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let orderList = ary{
                            //                            self.aryList.removeAllObjects()
                            if orderList.count > 0 {
                                
                                self.aryList.addObjectsFromArray(orderList)
                                self.dCurrentPage = self.dCurrentPage+1
                                if self.aryList.count >= self.dCurrentPage * 20 {
                                    self.isStartLoadingMore = false
                                }else{
                                    self.isStartLoadingMore = true
                                    self.tvList.tableFooterView = nil;
                                    return
                                    
                                }
                            }
                        }else{
                           self.isStartLoadingMore = false
//                            UIAlertView.show(nil, message: "没有更多订单", cancelButton: nil)
                            if self.BoolGetMore == false{
                                let alert:UIAlertView = UIAlertView(title: nil, message: "没有更多订单", delegate: self, cancelButtonTitle: "确定")
                                alert.tag = 10001
                                alert.show()
                                self.BoolGetMore = true
                            }
                        }
                        self.tvList.tableFooterView = UIView.init(frame: CGRectZero)
                        self.tvList.reloadData()
//                        self.tvList.tableFooterView = nil;
                    })
                    
                }else{
                    let dict = SHDataProvider.getDealerOrderList(["search_no":searchBar.text!,"account_type":"1","order_status":order_status,"dealer_id":SHDataProvider.getDealerID(),"page":"\(dCurrentPage+1)"])
                    //                    var dict = SHDataProvider.getDealerOrderList(["order_status": order_status,"dealer_id":SHDataProvider.getDealerID(),"page":"\(dCurrentPage+1)"])
                    
                    let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let orderList = ary{
                            //                            self.aryList.removeAllObjects()
                            if orderList.count > 0 {
                                
                                self.aryList.addObjectsFromArray(orderList)
                                self.dCurrentPage+=1
                                
                                if self.aryList.count >= self.dCurrentPage * 20 {
                                    self.isStartLoadingMore = false
                                }else{
                                    self.isStartLoadingMore = true
                                    self.tvList.tableFooterView = nil;
                                    return
                                }
                            }
                        }else{
                            self.isStartLoadingMore = false
                            if self.BoolGetMore == false{
                                let alert:UIAlertView = UIAlertView(title: nil, message: "没有更多订单", delegate: self, cancelButtonTitle: "确定")
                                alert.tag = 10001
                                alert.show()
                                self.BoolGetMore = true
                            }                        }
                        //                        self.isStartLoadingMore = false
                         self.tvList.tableFooterView = nil
                        self.tvList.reloadData()
                       
                        
                    })
            }
            
        }
    }
    
    override func navBack() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func statusChanged(sender: UISegmentedControl){
        if sender.selectedSegmentIndex==0{
            if !notice_status.hasPrefix("0") {
                notice_status = "0"
                refresh()
            }
        }else if sender.selectedSegmentIndex==1{
            if !notice_status.hasPrefix("1") {
                notice_status = "1"
                refresh()
            }
        }else{
            if !notice_status.hasPrefix("2"){
                notice_status = "2"
                refresh()
            }
        }
    }
    
    func showSelectedTakeCarPerson() {
        btnHide.hidden = false
        vMarkPerson.hidden = false
        tvListPerson.hidden = false
        vFooterPerson.hidden = false
        NSThread .detachNewThreadSelector(#selector(SHOrdersListViewController.loadGetCarPersonListData), toTarget: self, withObject: nil)
    }
    
    func hiddenTakeCarPerson() {
        btnHide.hidden = true
        vMarkPerson.hidden = true
        tvListPerson.hidden = true
        vFooterPerson.hidden = true
        vMark = nil
        btnHidePusPay = nil
        vPay = nil
        vMarkTabBar = nil
        var myDelegate:AppDelegate
        myDelegate = (UIApplication.sharedApplication().delegate as? AppDelegate)!
        
        vMarkTabBar = UIView(frame: CGRectMake(0,768-49,1024,49))
        vMarkTabBar.backgroundColor = UIColor.blackColor()
        vMarkTabBar.alpha = 0.5
        myDelegate.window?.addSubview(vMarkTabBar)
        
        btnHiddenMarkTabbar = UIButton (type: UIButtonType.Custom)
        btnHiddenMarkTabbar.frame = CGRectMake(0, 768-49, 1024, 768)
        btnHiddenMarkTabbar.backgroundColor = UIColor.clearColor()
        myDelegate.window?.addSubview(btnHiddenMarkTabbar)
        btnHiddenMarkTabbar.addTarget(self, action: #selector(SHOrdersListViewController.dismissShowViews), forControlEvents: .TouchUpInside)
        
        vMark = UIView(frame: CGRectMake(0,0,1024,768))
        vMark.backgroundColor = UIColor.blackColor()
        vMark.alpha = 0.5
        self.navigationController?.view.addSubview(vMark)

        btnHidePusPay = UIButton (type: UIButtonType.Custom)
        btnHidePusPay.frame = CGRectMake(0, 0, 1024, 768)
        btnHidePusPay.backgroundColor = UIColor.clearColor()
        self.navigationController?.view.addSubview(btnHidePusPay)
        btnHidePusPay.addTarget(self, action: #selector(SHOrdersListViewController.dismissShowViews), forControlEvents: .TouchUpInside)
        
        vPay = UIView(frame: CGRectMake(262,90,500,280))
        vPay.backgroundColor = UIColor.whiteColor()
        vPay.layer.cornerRadius = 10
        self.navigationController?.view.addSubview(vPay)

        
        tfPrice = UITextField.init(frame: CGRectMake(15, 15, 470, 50));
        tfPrice.clipsToBounds = true
        tfPrice.layer.cornerRadius = 4
        tfPrice.layer.borderWidth = 0.5
        tfPrice.keyboardType = .PhonePad
        tfPrice.delegate = self;
        tfPrice.placeholder = "请输入金额"
        tfPrice.backgroundColor = UIColor(white: 0.97, alpha: 1)
        tfPrice.layer.borderColor = UIColor(red: 0.58, green: 0.62, blue: 0.67, alpha: 1).CGColor
        tfPrice.layer.sublayerTransform = CATransform3DMakeTranslation(120, 0, 0)
        vPay.addSubview(tfPrice)
       
       
        let lbl: UILabel = UILabel.create(CGRectMake(20, 15, 106, tfPrice.frame.size.height), font: UIFont.systemFontOfSize(21), textColor: UIColor.blackColor())
        lbl.text = "消费金额："
        vPay.addSubview(lbl)


        
        for index in 0  ..< 3 {
            
            let newIndex  = index * 120
            
            imgvPhoto = UIImageView.init(frame: CGRectMake(15.0 + (CGFloat)(newIndex) , 85, 105, 105))
//            imgvPhoto.image = UIImage(named: "add_phont_icon")
            imgvPhoto.layer.cornerRadius = 10;
            imgvPhoto.clipsToBounds = true
            //            imgvPhoto.backgroundColor = UIColor.grayColor()
            imgvPhoto.userInteractionEnabled = true
            imgvPhoto.tag = 100+index
            if imgvPhoto.tag == 100{
                imgvPhoto.hidden = false
            }else{
                imgvPhoto.hidden = true
            }
            vPay .addSubview(imgvPhoto)
            
            var btn = UIButton(type: UIButtonType.Custom)
            btn.frame = imgvPhoto.frame
            btn.backgroundColor = UIColor.clearColor()
            vPay.addSubview(btn)
            btn.tag = index
            btn.addTarget(self, action: #selector(SHOrdersListViewController.showImage(_:)), forControlEvents: UIControlEvents.TouchUpInside)
            
            btn = UIButton(type: UIButtonType.Custom)
            btn.frame = CGRectMake(122+(CGFloat)(newIndex)-8.5, 77, 17, 16)
            btn.setBackgroundImage(UIImage(named:"btn_xx.png"), forState: UIControlState.Normal)
            btn.hidden = true
            vPay.addSubview(btn)
            btn.tag = index+6666
            btn.addTarget(self, action: #selector(SHOrdersListViewController.deleteIamgeForButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        }
        
        let btnAdd = UIButton(type: UIButtonType.Custom)
        btnAdd.frame = CGRectMake(15 + (CGFloat)(120*(0)), 85, 105, 105)
        btnAdd.setBackgroundImage(UIImage(named: "upload_photos.png"), forState: UIControlState.Normal)
        btnAdd.layer.cornerRadius = 10
        btnAdd.clipsToBounds = true
        vPay.addSubview(btnAdd)
        btnAdd.tag = 1000
        btnAdd.addTarget(self, action: #selector(SHOrdersListViewController.selectedPhotoClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        
        let btnCancel = UIButton(type: UIButtonType.Custom)
        btnCancel.frame = CGRectMake(15, vPay.frame.size.height-15-45, 223, 45)
        btnCancel.setBackgroundImage(UIImage(named: "cancel_button.png"), forState: UIControlState.Normal)
        btnCancel.setTitle("取消", forState: UIControlState.Normal)
        btnCancel.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
        vPay.addSubview(btnCancel)
        btnCancel.addTarget(self, action: #selector(SHOrdersListViewController.btnCancelClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        
        let btnCommit = UIButton(type: UIButtonType.Custom)
        btnCommit.frame = CGRectMake(253, vPay.frame.size.height-15-45, 223, 45)
        btnCommit.backgroundColor = UIColor(red: 0.17, green: 0.52, blue: 0.80, alpha: 1)
        btnCommit.setTitle("确定", forState: UIControlState.Normal)
        btnCommit.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        vPay.addSubview(btnCommit)
        btnCommit.addTarget(self, action: #selector(SHOrdersListViewController.btnCommitClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        
//         tfPrice.becomeFirstResponder()
    }
    
    func btnCancelClicked(sender:UIButton){
        tfPrice.resignFirstResponder()
        vPay.hidden = true
        vMarkTabBar.hidden = true
        btnHiddenMarkTabbar.hidden = true
        vMark.hidden = true
    }
    
    
    func deleteIamgeForButton(sender:UIButton){
        let index = sender.tag-6666
        if aryPhotosURI.count > 0{
            aryPhotosURI.removeObjectAtIndex(index)
            aryPhotos.removeObjectAtIndex(index)
            self.refreshButtons()
        }
    }
    
    // MARK: - UITableView Delegate & Data Source
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if tableView == tvList {
            let identifier = "OrderCell"
            var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as UITableViewCell!
            
            if cell==nil{
                cell = UITableViewCell(style: .Default, reuseIdentifier: identifier)
                cell.contentView.layer.borderWidth = 0.5
                cell.contentView.layer.borderColor = UIColor(red: 0.82, green: 0.84, blue: 0.86, alpha: 1).CGColor
                cell.contentView.backgroundColor = UIColor(red: 0.97, green: 0.98, blue: 0.99, alpha: 1)
                cell.selectionStyle = .None
                
                var imgv = UIImageView.init(frame: CGRectMake(10, 12.5, 55, 20))
                imgv.tag = 800
                cell.contentView.addSubview(imgv)
                
                imgv = UIImageView.init(frame: CGRectMake(10+55+5, 12.5, 0, 0))
                imgv.tag = 801
                cell.contentView.addSubview(imgv)
                
                let cancleWatermark = UIImageView.init(frame: CGRect.init(x: tvList.frame.size.width-70, y: 90, width: 70, height: 54))
                cancleWatermark.tag = 300
                cancleWatermark.hidden = true
                cancleWatermark.image = UIImage.init(named: "cancelWatermark")
                cell.contentView.addSubview(cancleWatermark)
                
                var titles = "预约人，联系电话，预约时间，服务方式，创建时间，车辆型号".componentsSeparatedByString("，")
                for i in 0 ..< titles.count{
                    let col = i % 2
                    let row = i / 2
                    var lbl = UILabel.create(CGRectMake(CGFloat(10+195*col), CGFloat(60+25*row), 60, 13), font: UIFont.systemFontOfSize(12), textColor: UIColor.grayColor())
                    lbl.text = titles[i]
                    lbl.tag = 900+i
                    cell.contentView.addSubview(lbl)
                    
                    lbl = UILabel.create(CGRectMake(CGFloat(70+190*col), CGFloat(60+25*row), 130, 14), font: UIFont.systemFontOfSize(12), textColor: UIColor.blackColor())
                    lbl.text = titles[i]
                    lbl.tag = 1000+i
                    cell.contentView.addSubview(lbl)
                }
                
                let cellline = UIView(frame: CGRectMake(0, 145, tvList.frame.size.width, 10))
                cellline.backgroundColor = UIColor(red: 0.96, green: 0.96, blue: 0.98, alpha: 1)
                cell.contentView.addSubview(cellline)
                
                var lbl: UILabel = UILabel.create(CGRectMake(370-160, 0, 150, 45), font: UIFont.systemFontOfSize(12), textColor: UIColor(red: 0.29, green: 0.56, blue: 0.89, alpha: 1))
                lbl.textAlignment = .Right
                lbl.tag = 100
                cell.contentView.addSubview(lbl)
                
                lbl = UILabel.create(CGRectMake(70, 0, 250, 45), font: UIFont.systemFontOfSize(12), textColor: UIColor.grayColor())
                lbl.tag = 101
                cell.contentView.addSubview(lbl)

                let line = UIView(frame: CGRectMake(0, 44.5, 370, 0.5))
                line.backgroundColor = UIColor(white: 0.88, alpha: 1)
                cell.contentView.addSubview(line)
                
                let circle = UIView(frame: CGRectMake(0, 0, 8, 8))
                circle.clipsToBounds = true
                circle.layer.cornerRadius = 4
                circle.backgroundColor = UIColor.whiteColor()
                circle.tag = 200
                cell.contentView.addSubview(circle)
                circle.center = CGPointMake(370-18, 66)
                circle.hidden = true
            }
            //服务内容 保养维修
            let imgvServiceType1 = cell.contentView.viewWithTag(800) as! UIImageView!
            let imgvServiceType2 = cell.contentView.viewWithTag(801) as! UIImageView!

            let lblStatus = cell.contentView.viewWithTag(100) as! UILabel!
            let lblOrderNo = cell.contentView.viewWithTag(101) as! UILabel!
            
            //标题名字
            let lblTitle1 = cell.contentView.viewWithTag(900) as! UILabel!
            let lblTitle2 = cell.contentView.viewWithTag(901) as! UILabel!
            let lblTitle3 = cell.contentView.viewWithTag(902) as! UILabel!
            let lblTitle4 = cell.contentView.viewWithTag(903) as! UILabel!
            let lblTitle5 = cell.contentView.viewWithTag(904) as! UILabel!
            let lblTitle6 = cell.contentView.viewWithTag(905) as! UILabel!
            
            let lblName = cell.contentView.viewWithTag(1000) as! UILabel!
            let lblPhone = cell.contentView.viewWithTag(1001) as! UILabel!
            let lblOrderTime = cell.contentView.viewWithTag(1002) as! UILabel!
            let lblOrderType = cell.contentView.viewWithTag(1003) as! UILabel!
            let lblStartTime = cell.contentView.viewWithTag(1004) as! UILabel!
            let lblCarType = cell.contentView.viewWithTag(1005) as! UILabel!
            let circle = cell.contentView.viewWithTag(200)!
            let cancleWatermark = cell.contentView.viewWithTag(300) as! UIImageView!
            cancleWatermark.hidden = true
            
            let orderInfo = aryList[indexPath.row]
            lblStartTime.hidden = false
            lblName.text = orderInfo.objectForKey("name") as! String?
            lblOrderTime.text = "".stringByAppendingString(orderInfo.objectForKey("order_time") as! String!)
            lblStartTime.text = "".stringByAppendingString(orderInfo.objectForKey("create_time") as! String!)
            
            if let strCarType = orderInfo.objectForKey("car_info")?.objectForKey("abbr_name"){
                lblCarType.text = "\(strCarType)"
            }else{
                lblCarType.text = "海马M6"
            }
            
            

                if let phone = orderInfo.objectForKey("order_phone") as! String!{
                    lblPhone.text = "\(phone)"
                }else if let phone = orderInfo.objectForKey("phone") as! String!{
                    lblPhone.text = "\(phone)"
                }else{
                    lblPhone.text = ""
                }
            //               order_deal_status  dealer_handle_type
            if let dealer_handle_type = orderInfo.objectForKey("dealer_handle_type")?.integerValue as Int!{
                if 1 == dealer_handle_type{//UIColor(red: 0.27, green: 0.55, blue: 0.9, alpha: 1)
                    circle.hidden = true
                    circle.backgroundColor = ORANGECOLOR
                    //                        circle.backgroundColor = UIColor(red: 0.99, green: 0.84, blue: 0.19, alpha: 1)
                }else{
                    circle.hidden = true
                    //                        circle.backgroundColor = UIColor.greenColor()
                }
            }
                if orderInfo===selectedOrder{
                    cell.contentView.backgroundColor = ORANGECOLOR
                    circle.backgroundColor = UIColor.whiteColor()
//                    cellIndexImage.image = UIImage(named: "bule_all_orders.png")
//                    cellIndexImage.hidden = false
                    lblOrderNo.textColor = UIColor.whiteColor()
                    lblStatus.textColor = UIColor.whiteColor()
                    lblName.textColor = UIColor.whiteColor()
                    lblPhone.textColor = UIColor.whiteColor()
                    lblOrderTime.textColor = UIColor.whiteColor()
                    lblOrderType.textColor = UIColor.whiteColor()
                    lblStartTime.textColor = UIColor.whiteColor()
                    lblCarType.textColor = UIColor.whiteColor()
                    
                    lblTitle1.textColor = UIColor.whiteColor()
                    lblTitle2.textColor = UIColor.whiteColor()
                    lblTitle3.textColor = UIColor.whiteColor()
                    lblTitle4.textColor = UIColor.whiteColor()
                    lblTitle5.textColor = UIColor.whiteColor()
                    lblTitle6.textColor = UIColor.whiteColor()
                    
                    cancleWatermark.image = UIImage.init(named: "cancelWatermarkSelect")
                    
                    if let orderType = orderInfo.objectForKey("order_type")?.intValue{
                        lblOrderType.hidden = false
                        if 1==orderType{
                            imgvServiceType1.image = UIImage(named: "maintain_seleted.png")//
                            imgvServiceType2.frame = CGRectMake(70, 12.5, 0, 0)
                            lblOrderType.text = "保养"
                        }else if 2==orderType{
                            imgvServiceType1.image = UIImage(named: "repair_seleted.png")//
                            imgvServiceType2.frame = CGRectMake(70, 12.5, 0, 0)
                            lblOrderType.text = "维修"
                        }else{
                            lblOrderType.text = "维修和保养"
                            imgvServiceType1.image = UIImage(named: "maintain_seleted.png")//
                            imgvServiceType2.image = UIImage(named: "repair_seleted.png")//
                            imgvServiceType2.frame = CGRectMake(70, 12.5, 55, 20)
                        }
                    }else{
                        lblOrderType.hidden = true
                    }
                    
                    if imgvServiceType2.frame.size.width > 0 {
                        lblOrderNo.frame = CGRectMake(70+imgvServiceType2.frame.size.width+5, 0, 250, 45)
                      
                    }else{
                       lblOrderNo.frame = CGRectMake(70+imgvServiceType2.frame.size.width, 0, 250, 45)
                    }
                    
                    if let checkNo = orderInfo.objectForKey("check_no") as! String!{
                        lblOrderNo.text = "预约单号：\(checkNo)"
                    }else{
                        lblOrderNo.text = "预约单号：";
                    }
                   
                }else{
                    cell.contentView.backgroundColor = UIColor.whiteColor()
                    circle.backgroundColor = ORANGECOLOR
//                    cellIndexImage.image = nil
//                    cellIndexImage.hidden = true
                    lblOrderNo.textColor = UIColor.grayColor()
                    lblStatus.textColor =  ORANGECOLOR
                    lblName.textColor = UIColor.blackColor()
                    lblPhone.textColor = UIColor.blackColor()
                    lblOrderTime.textColor = UIColor.blackColor()
                    lblOrderType.textColor = UIColor.blackColor()
                    lblStartTime.textColor = UIColor.blackColor()
                    lblCarType.textColor = UIColor.blackColor()
                    
                    lblTitle1.textColor = UIColor.grayColor()
                    lblTitle2.textColor = UIColor.grayColor()
                    lblTitle3.textColor = UIColor.grayColor()
                    lblTitle4.textColor = UIColor.grayColor()
                    lblTitle5.textColor = UIColor.grayColor()
                    lblTitle6.textColor = UIColor.grayColor()
                    
                    cancleWatermark.image = UIImage.init(named: "cancelWatermark")
                    
                    if let orderType = orderInfo.objectForKey("order_type")?.intValue{
                        lblOrderType.hidden = false
                        if 1==orderType{
                            imgvServiceType1.image = UIImage(named: "maintain_nor.png")//maintain_seleted.png
                            imgvServiceType2.frame = CGRectMake(70, 12.5, 0, 0)
                            lblOrderType.text = "保养"
                        }else if 2==orderType{
                            imgvServiceType1.image = UIImage(named: "repair_normal.png")//repair_seleted.png
                            imgvServiceType2.frame = CGRectMake(70, 12.5, 0, 0)
                            lblOrderType.text = "维修"
                        }else{
                            lblOrderType.text = "维修和保养"
                            imgvServiceType1.image = UIImage(named: "maintain_nor.png")//maintain_seleted.png
                            imgvServiceType2.image = UIImage(named: "repair_normal.png")//repair_seleted.png
                            imgvServiceType2.frame = CGRectMake(70, 12.5, 55, 20)
                        }
                    }else{
                        lblOrderType.hidden = true
                    }
                    
                    if imgvServiceType2.frame.size.width > 0 {
                        lblOrderNo.frame = CGRectMake(70+imgvServiceType2.frame.size.width+5, 0, 250, 45)
                        
                    }else{
                        lblOrderNo.frame = CGRectMake(70+imgvServiceType2.frame.size.width, 0, 250, 45)
                    }
                    if let checkNo = orderInfo.objectForKey("check_no") as! String!{
                        lblOrderNo.text = "预约单号：\(checkNo)"
                    }else{
                        lblOrderNo.text = "预约单号：";
                    }
                    
                }
            
                if let order_statuss = orderInfo.objectForKey("order_status")?.integerValue as Int!{
                    if 1 == order_statuss{
                        lblStatus.text  = "已发起"
                    }else if 2 == order_statuss{
                        lblStatus.text  = "未成功"
                    }else if 3 == order_statuss{
                        lblStatus.text  = "已接受"
                    }else if 4 == order_statuss{
                        if let back_type = orderInfo.objectForKey("back_type")?.integerValue as Int! {
                            if back_type == 1 {
                                lblStatus.text = "待评价"
                                
                            }else{
                                lblStatus.text = "待评价"//服务中
                            }
                        }
                        
                    }else if 5 == order_statuss{
                        lblStatus.text  = "已评价"
                    }else if 6 == order_statuss{
                        lblStatus.text  = "待取车"
                    }else if 7 == order_statuss{
                        lblStatus.text  = "服务中"
                    }else if 8 == order_statuss{
                        lblStatus.text  = "服务中"
                    }else if 9 == order_statuss{
                        if  let pick_type = orderInfo.objectForKey("pick_type")?.integerValue as Int!{
                            if pick_type == 1{
//                                lblStatus.text  = "待付款"
                                lblStatus.text  = "服务中"
                            }else{
                                lblStatus.text  = "服务中"
                                
                            }
                        }
                        
                    }else if 10 == order_statuss{
                        lblStatus.text  = "待付款"
                    }else if 11 == order_statuss{
                        if let back_type = orderInfo.objectForKey("back_type")?.integerValue as Int! {
                            if back_type == 1 {
                                lblStatus.text = "待送车"//待评价
                                
                            }else{
                                lblStatus.text = "待送车"
                            }
                        }
                    }else if 12 == order_statuss{
                        lblStatus.text  = "服务中"//待评价
                    }else if 13 == order_statuss{
                        lblStatus.text  = "已取消"
                        cancleWatermark.hidden = false
                    }else if 14 == order_statuss{
                        lblStatus.text  = "待确认"
                    }else if 15 == order_statuss{
                        lblStatus.text  = "已接受"
                    }else if 16 == order_statuss{
                        lblStatus.text  = "付款中"
                    }else if 17 == order_statuss{
                        lblStatus.text  = "服务中"
                    }else{
                        lblStatus.text  = "已发起"
                    }
                    
                }
                
            
            
            return cell
            
        }else if tableView == tvListClass{
            let identifier = "ClassCell"
            var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as UITableViewCell!
            
            if cell==nil{
                cell = UITableViewCell(style: .Default, reuseIdentifier: identifier)
                cell.layer.borderWidth = 0.5
                cell.layer.borderColor = UIColor(red: 0.82, green: 0.84, blue: 0.86, alpha: 1).CGColor

                cell.contentView.backgroundColor = UIColor.whiteColor()
                cell.selectionStyle = .None
                
                let lbl = UILabel.create(CGRectMake(10, 0, 200, 44), font: UIFont.systemFontOfSize(14), textColor: UIColor.blackColor())
                lbl.tag = 2000
                cell.contentView.addSubview(lbl)

            }
            let lblClassName = cell.contentView.viewWithTag(2000) as! UILabel!

            lblClassName.text = aryClassList.objectAtIndex(indexPath.row) as? String
            if lastIndex == indexPath.row{
                lblClassName.textColor = UIColor(red: 0.29, green: 0.56, blue: 0.89, alpha: 1)
                cell.accessoryType = UITableViewCellAccessoryType.Checkmark
            }else{
                lblClassName.textColor = UIColor.grayColor()
                cell.accessoryType = UITableViewCellAccessoryType.None
            }
            
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            return cell
        }
        
        
        let identifierTake = "takeIdentifier"
        var cell = tableView.dequeueReusableCellWithIdentifier(identifierTake) as UITableViewCell!
        
        if cell==nil{
            cell = UITableViewCell(style: .Default, reuseIdentifier: identifierTake)
            cell.contentView.layer.borderWidth = 0.5
            cell.contentView.layer.borderColor = UIColor(red: 0.82, green: 0.84, blue: 0.86, alpha: 1).CGColor
            cell.contentView.backgroundColor = UIColor(red: 0.97, green: 0.98, blue: 0.99, alpha: 1)
            cell.selectionStyle = .None
            
            
            var imgv = SWImageView(frame: CGRectMake(50, 20, 60, 60))
            imgv.backgroundColor = UIColor.whiteColor()
            imgv.layer.cornerRadius = 30.0
            imgv.clipsToBounds = true
            imgv.tag = 1000
            imgv.delegate = self
            cell.contentView.addSubview(imgv)
            
            imgv = SWImageView(frame: CGRectMake(15, 40, 20, 20))
            imgv.image = UIImage(named: "normal")
            imgv.layer.cornerRadius = 3.0
            imgv.tag = 1005
            imgv.delegate = self
            cell.contentView.addSubview(imgv)
            
            var lbl = UILabel.create(CGRectMake(120, 20, 230, 18), font: UIFont.systemFontOfSize(18), textColor: UIColor.blackColor())
            lbl.tag = 1001
            cell.contentView.addSubview(lbl)
            
            lbl = UILabel.create(CGRectMake(120, 45, 230, 18), font: UIFont.systemFontOfSize(15), textColor: UIColor.grayColor())
            lbl.tag = 1002
            cell.contentView.addSubview(lbl)
            
            lbl = UILabel.create(CGRectMake(120, 70, 230, 18), font: UIFont.systemFontOfSize(15), textColor: UIColor.grayColor())
            lbl.tag = 1003
            cell.contentView.addSubview(lbl)
        }

        let lblPersonName = cell.contentView.viewWithTag(1001) as! UILabel!
        let lblPersonPhone = cell.contentView.viewWithTag(1002) as! UILabel!
        let lblPersonNumber = cell.contentView.viewWithTag(1003) as! UILabel!
        let imgvPersonPortrait = cell.contentView.viewWithTag(1000) as! SWImageView!
        let imgvPersonSelected = cell.contentView.viewWithTag(1005) as! SWImageView!
       
        let personInfo = aryPersonList[indexPath.row]
        lblPersonName.text = personInfo.objectForKey("name") as! String?
        lblPersonPhone.text = personInfo.objectForKey("telephone") as! String?
        lblPersonNumber.text = personInfo.objectForKey("work_no") as! String?
        
        imgvPersonPortrait.image = UIImage(named: "portrait")
        
        if IndexSelected == indexPath.row && isSelectedPerson == true{
            imgvPersonSelected.image = UIImage(named: "seleted")
            cell.contentView.backgroundColor = ORANGECOLOR
            lblPersonName.textColor = UIColor.whiteColor()
            lblPersonPhone.textColor = UIColor.whiteColor()
            lblPersonNumber.textColor = UIColor.whiteColor()
        }else{
            imgvPersonSelected.image = UIImage(named: "normal")
            cell.contentView.backgroundColor = UIColor.whiteColor()
            //            cell.selected = false
            lblPersonName.textColor = UIColor.blackColor()
            lblPersonPhone.textColor = UIColor.grayColor()
            lblPersonNumber.textColor = UIColor.grayColor()
        }

        cell.selectionStyle = UITableViewCellSelectionStyle.Blue
        return cell
    }
    
    func downimage(url : NSString){
        
        let urlStr:NSString  = url
        
        let  request:NSURLRequest = NSURLRequest(URL: NSURL(string: urlStr as String)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval:2.0)
        
        NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue()) { (response, data, error) ->Void in
            
            let  path:NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory,NSSearchPathDomainMask.UserDomainMask,true)[0];
            
            let  cachepaht = path.stringByAppendingPathComponent("test.png")
            
            data?.writeToFile(cachepaht, atomically:true);
        }
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if tableView == tvList{
            return 155
        }else if tableView == tvListClass{
            return 44
        }
        return 100.0
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //        return aryList.count
        
        if tableView == tvList{
            return aryList.count
        }else if tableView == tvListClass{
            return aryClassList.count
        }
        return aryPersonList.count
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        var v = UIView()
        
            v = UIView(frame: CGRectMake(0, 0, 370, 30))
            v.backgroundColor = UIColor(white: 0.97, alpha: 1)
        
            let imgvClass = UIImageView(frame: CGRectMake(10, 7.5, 15, 15))
            imgvClass.image = UIImage(named: "menu.png")
            v.addSubview(imgvClass)
        
            let lblClass = UILabel(frame: CGRectMake(30, 0, 30, 30))
            lblClass.font = UIFont.systemFontOfSize(12)
            lblClass.textColor = UIColor.grayColor()
            v.addSubview(lblClass)
            lblClass.text = "类别"
        
        
            let btnClass: UIButton = UIButton(frame: CGRectMake(0, 0, 60, 30))
            btnClass.backgroundColor = UIColor.clearColor()

            btnClass.addTarget(self, action: #selector(SHOrdersListViewController.btnClassClicked), forControlEvents: .TouchUpInside)
            v.addSubview(btnClass)
        
            lblSelectedClass = UILabel(frame: CGRectMake(70, 0, 290, 30))
            lblSelectedClass.font = UIFont.systemFontOfSize(12)
            lblSelectedClass.textColor = ORANGECOLOR
            v.addSubview(lblSelectedClass)
            lblSelectedClass.text = strDefaultClass
        
        
           let btnAllClass: UIButton = UIButton(frame: CGRectMake(60, 0, 70, 30))
            btnAllClass.backgroundColor = UIColor.clearColor()
            btnAllClass.addTarget(self, action: #selector(SHOrdersListViewController.btnAllClassClicked), forControlEvents: .TouchUpInside)
            v.addSubview(btnAllClass)
            btnAllClass.hidden = true

            
            if isFromSearchOrder == true{
                btnShowSearch = UIButton(frame: CGRectMake(270, 15, 40, 20))
                btnShowSearch.setImage(UIImage(named: "btn_down"), forState: UIControlState.Normal)
                btnShowSearch.setImage(UIImage(named: "up"), forState: UIControlState.Selected)
                btnShowSearch.addTarget(self, action: #selector(SHOrdersListViewController.userSelectSearch(_:)), forControlEvents: .TouchUpInside)
                v.addSubview(btnShowSearch)
            }

        return v
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if tableView == tvList{

                switch section{
                case 0:
                    return 30
                default:
                    return 0.0
                }

        }
        
        return 0.0
    }
 
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        if tableView == tvList{
                 searchBar.resignFirstResponder()
                let orderInfo: AnyObject = aryList[indexPath.row]
                vAllOrders.OrdersInfo = orderInfo as? NSDictionary
                //                vNotificationDetail.orderNotificationInfo = orderInfo as? NSDictionary
                selectedOrder = orderInfo as? NSDictionary
                vAllOrders.number = indexPath.row
                checkNo = orderInfo.objectForKey("check_no") as? String
                tvList.reloadData()
            
        }else if tableView == tvListClass{
            strDefaultClass = aryClassList[indexPath.row] as! String
            let a = indexPath.row
            if a != lastIndexPath{
                lastIndex = a
                let newCell = tableView.cellForRowAtIndexPath(indexPath)
                newCell?.accessoryType = UITableViewCellAccessoryType.Checkmark
                let oldCell = tableView.cellForRowAtIndexPath(lastIndexPath)
                oldCell?.accessoryType = UITableViewCellAccessoryType.None
                
                lastIndexPath = indexPath
                lastIndex = indexPath.row
                 tableView.deselectRowAtIndexPath(indexPath, animated: true)
                
                tableView.reloadData()

            }
            
            tvListClass.hidden = true
            vMarkClass.hidden = true
            btnHideClass.hidden = true

            switch indexPath.row{
            case 0:
                order_status = "0"
            case 1:
                order_status = "1"
            case 2:
                order_status = "3"
            case 3:
                order_status = "1,3,6,7,8,9,10,11,12,14,15,16"
            case 4:
                order_status = "10,16"
            case 5:
                order_status = "4"
            case 6:
                order_status = "5"
            case 7:
                order_status = "13"
            case 8:
                order_status = "14,15"

                default:()
            }
            
            self.refresh()
            
        }else{
            dicSelectedPersonInfo = aryPersonList[indexPath.row] as? NSDictionary
            isSelectedPerson = true
            IndexSelected = indexPath.row
            tvListPerson.reloadData()
            
        }
        
    }
    

    //订单类别选择
    func btnClassClicked (){
        vMarkClass.hidden = false
        btnHideClass.hidden = false
        tvListClass.hidden = false
    }
    //所有类别
    func btnAllClassClicked(){
        vMarkClass.hidden = true
        btnHideClass.hidden = true
        tvListClass.hidden = true
        order_status = "0"
        self.refresh()
    }
    
    //MARK: - MHOrderDetail Delegate
    func orderUpdated(order: NSDictionary?) {
        if let dict = order{
            let order_id = dict.objectForKey("order_id")?.intValue!
            for i in 0 ..< aryList.count{
                let oi = aryList[i].objectForKey("order_id")?.intValue!
                
                if order_id==oi{
                    aryList.replaceObjectAtIndex(i, withObject: dict)
                    break
                }
            }
            
            tvList.reloadData()
        }
    }
    
    //MARK: -显示搜索条件
    func userSelectSearch(sender:UIButton){
        print("显示搜索条件")
        sender.selected = true
        
        vMarkSearch.hidden = false
        //        vSearchOrderView.hidden = false
        imgvSearchBG.hidden = false
        
    }
    //MARK: - MHAllOrders Delegate
    func allOrdesUpdated(order: NSDictionary?) {
        if let dict = order{
            let order_id = dict.objectForKey("order_id")?.intValue!
            for i in 0 ..< aryList.count{
                let oi = aryList[i].objectForKey("order_id")?.intValue!
                
                if order_id==oi{
                    aryList.replaceObjectAtIndex(i, withObject: dict)
                    break
                }
            }
            
            tvList.reloadData()
        }
    }
    
    func selectedPhotoClicked(sender: UIButton){
        tfPrice.resignFirstResponder()
        let actionSheet = UIActionSheet()
        actionSheet.title = "选择要进行的操作"
        actionSheet.delegate = self
        actionSheet.addButtonWithTitle("相册")
        actionSheet.addButtonWithTitle("拍照")
        actionSheet.addButtonWithTitle("取消")
       actionSheet.showInView(self.view)
//        var myDelegate:AppDelegate
//        myDelegate = (UIApplication.sharedApplication().delegate as? AppDelegate)!
//        actionSheet.showFromRect(CGRectMake(sender.frame.origin.x,sender.frame.origin.y,200, 300), inView:self.view, animated: true)
        
//        actionSheet.showInView((UIApplication.sharedApplication().keyWindow!.rootViewController?.view)!)
        
        
//        if #available(iOS 8.0, *) {
//            let act = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
//            
//            var logoutAction = UIAlertAction(title: "注销", style: UIAlertActionStyle.Default){
//                (action: UIAlertAction!) -> Void in
////                println("you choose delete")
//            }
//            
//            var cancleAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Default){
//                (action: UIAlertAction!) -> Void in
//                //                println("you choose delete")
//            }
//            act.addAction(logoutAction)
//            act.addAction(cancleAction)
//            
//            
//        } else {
//            // Fallback on earlier versions
//        }
        
    }
    
    func showImage(sender: UIButton){
        
    }
    
    func btnCommitClicked(sender: UIButton){
       
        
        strPrice  = self.tfPrice.text! as NSString
        
        if strPrice.length == 0 || strPrice.floatValue <= 0 {
//            HYBProgressHUD.showError("请输入金额！")
            UIAlertView.show(nil, message: "请输入金额！", cancelButton: nil)
            return
            
        }else if aryPhotosURI.count <= 0 {
            UIAlertView.show(nil, message: "最少上传一张清单", cancelButton: nil)
            return
        }
        else{
             tfPrice.resignFirstResponder()
            vPay.hidden = true
            vMarkTabBar.hidden = true
            btnHiddenMarkTabbar.hidden = true
            vMark.hidden = true
            self.endService()
        }
        
        
        
    }
    
    
    //服务完成
    func endService(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                if let order_id = self.vAllOrders.OrdersInfo?.objectForKey("order_id") as! String!{
                    let str = NSMutableString()
                    if self.aryPhotosURI.count > 0{
                        for i in 0 ..< self.aryPhotosURI.count{
                            
                            let key = self.aryPhotosURI[i]
                            str.appendString(key as! String)
                            str.appendString(",")
                            
                        }
                    }
                    
                    
                    let dicParams = ["order_id" : order_id, "price" : self.strPrice, "photo_uris" : str]
                    let dict = SHDataProvider.endService(dicParams)
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                                let mut = NSMutableDictionary(dictionary: self.vAllOrders.OrdersInfo!) as NSMutableDictionary
                                mut.setObject("4", forKey: "order_status")
                                
//                                self.vAllOrders.OrdersInfo = NSDictionary(dictionary: mut)
                                self.vAllOrders.OrdersInfo =  NSDictionary(dictionary: (dict?.objectForKey("data"))! as! [NSObject : AnyObject])
                            }else{
                                if let msg = dict?.objectForKey("message") as? String{
                                    UIAlertView.show(nil, message: msg, cancelButton: nil)
                                }else{
                                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                                }
                            }
                        }else{
                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                        self.getNewOrderDetail()
//                        self.allOrdesUpdated(self.vAllOrders.allOrdersInfo)
                    })
                }
            })
        }
    }
    //等待处理订单数
    func getWaitingOrdersCounts(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                
                let dict = SHDataProvider.getWaitDealsum(["dealer_id":SHDataProvider.getDealerID()])
                print(dict)

                SWUtils.RunOnMainThread({ () -> Void in
                    if let code = dict?.objectForKey("code")?.intValue{
                        if code==200{
                            var ordercount = dict?.objectForKey("data")?.objectForKey("count")?.integerValue
                            if ordercount >= 0    {
                                
                                ordercount = 0
//                                if let oldCount:Int = NSUserDefaults.standardUserDefaults().integerForKey("OrdersCount"){
//                                    if oldCount != ordercount{
//                                        self.refresh()
//                                    }
//                                }
                                NSUserDefaults.standardUserDefaults().setInteger(ordercount!, forKey: "OrdersCount");
                                NSNotificationCenter.defaultCenter().postNotificationName("ChangeWaitBadge", object: nil)
                            }else{
                                NSUserDefaults.standardUserDefaults().setInteger(0, forKey: "OrdersCount");
                                NSNotificationCenter.defaultCenter().postNotificationName("ChangeWaitBadge", object: nil)
                            }
                            
                        }else{
                            
                        }
                    }else{
                        
                    }
                    
                })
            })
        }

    }
    
    //获取最新订单详情
    func getNewOrderDetail(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                if let order_id = self.vAllOrders.OrdersInfo?.objectForKey("order_id") as! String!{
                    let dict = SHDataProvider.getOrderDetail(["order_id":order_id,"account_type":"1"])
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                let dic = NSDictionary(dictionary: (dict?.objectForKey("data"))! as! [NSObject : AnyObject])
                                self.vAllOrders.OrdersInfo = dic
                                //                                self.allOrdesUpdated(self.vAllOrders.allOrdersInfo)
                                
                            }else{
                                
                            }
                        }else{
                            //                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                        //                        self.updateAllOrdersInfo()
                    })
                }
            })
        }
        
    }
    
    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        btnResignSearchBar.hidden = false
    }
    // 输入框内容改变触发事件
    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

        print("过滤：(searchText)")
    }
    // 书签按钮触发事件
    func searchBarBookmarkButtonClicked(searchBar: UISearchBar) {
        print("搜索历史")
        
    }
    
    // 取消按钮触发事件
    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        print("取消搜索")
        btnResignSearchBar.hidden = true
        searchBar.resignFirstResponder()
    }
    
    // 搜索触发事件
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        print("开始搜索")
        btnResignSearchBar.hidden = true
        searchBar.resignFirstResponder()
        
        self.loadData()
    }
    
    
    func searchStart(){
        //        order_status = "0";
        let dict = SHDataProvider.getDealerOrderList(["search_no":searchBar.text!,"account_type":"1","order_status":order_status,"dealer_id":SHDataProvider.getDealerID()])
        
        //            var dict = SHDataProvider.getDealerOrderList(["dealer_id":SHDataProvider.getDealerID()])
        
        let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
        
        SWUtils.RunOnMainThread({ () -> Void in
            if let orderList = ary{
                self.aryList.removeAllObjects()
                self.aryList = NSMutableArray(array: orderList)
                
                if orderList.count>0{
                    let formatter = NSDateFormatter()
                    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
                    let d = formatter.dateFromString(orderList[0].objectForKey("create_time") as! String)
                    if let dd = d{
                        NSUserDefaults.standardUserDefaults().setObject(dd, forKey: "LatestOrderTime")
                    }
                }
            }else{
                self.aryList.removeAllObjects()
            }
            
            self.tvList.reloadData()
            self.refreshController.endRefreshing()
            
            if self.aryList.count>0{
                self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))
            }else{
                
            }
            
            
        })
        
    }
    
    // MARK: - UIActionSheet Delegate
    func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {
        imagePicker = nil
 
        if buttonIndex >=  0 {
            let buttonTitle = actionSheet.buttonTitleAtIndex(buttonIndex)
            
            if buttonTitle=="拍照"{
                if UIImagePickerController.isSourceTypeAvailable(.Camera){
                    vMarkTabBar.hidden = true
                    btnHiddenMarkTabbar.hidden = true
                    imagePicker = UIImagePickerController()
                    imagePicker.delegate = self
                    imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
                    imagePicker.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
                    imagePicker.supportedInterfaceOrientations()
                    imagePicker.allowsEditing = true
                    self.presentViewController(imagePicker, animated: true, completion: nil)
                    //                    pop = nil
                    //                    pop = UIPopoverController.init(contentViewController: imagePicker)
                    //                    pop.popoverContentSize = CGSizeMake(UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)
                    //                    pop.presentPopoverFromRect(CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height), inView:self.view, permittedArrowDirections: .Any, animated: true)
                }
                
                
                
            }else if buttonTitle == "相册"{
                if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
                    imagePicker = UIImagePickerController()
                    imagePicker.delegate = self
                    imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                    imagePicker.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
                    imagePicker.allowsEditing = true
                    //            self.presentViewController(imagePicker, animated: true, completion: nil)
                    pop = nil
                    pop = UIPopoverController.init(contentViewController: imagePicker)
                    pop.popoverContentSize = CGSizeMake(500, 500)
                    
                    pop.presentPopoverFromRect(CGRectMake(0, 0, 500, 500), inView: self.view, permittedArrowDirections: .Any, animated: true)
                }
                
            }else{
                
            }
            
        }
        
    }
    
    // MARK -UIImagePikerControllerDelegate
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        var imageToSave:UIImage
        //UIImagePickerControllerEditedImage,这个需要特别注意，根据需要获得不同的图片，此处这个参数代表得到编辑完的图片，还有其他函数QAQ被坑了一晚
        imageToSave = info[UIImagePickerControllerEditedImage] as! UIImage
        //获取到相机拍出来的视频，userImage为我view里的image view控件名称，自行更改
        
        //        imgvPhoto.image = image
        let imgdata = UIImageJPEGRepresentation(imageToSave, 0.05)
        let strImgHash = imgdata?.SHA1String() as String!
        let strHashPath = strImgHash?.imageCachePath() as String!
        imgdata?.writeToFile(strHashPath!, atomically: false)
        
        if BoolIsUsedOSS == true {
              var put = OSSPutObjectRequest.init()
              put.bucketName = OSSBucket
              put.objectKey = strImgHash
              put.uploadingData = imgdata
            self.initOSSCliect()
             var putTask = client.putObject(put)
            putTask.continueWithBlock({
                task  in
                print("objectkey:\(put.objectKey)")
                if task.error == nil {
                    print("upload object success!")
                    self.realkey = put.objectKey
                    do {
                        try  NSFileManager.defaultManager().removeItemAtPath(strHashPath)
                    } catch {
                        //
                    }
                    defer {
                       print("Do clean up here")
                    }
                   
                    SWUtils.RunOnMainThread({ () -> Void in
                        HYBProgressHUD.showSuccess("清单上传成功")
                        self.aryPhotos.addObject(imageToSave)
                        if self.realkey != nil && self.realkey?.length != 0{
                            self.aryPhotosURI.addObject(self.realkey!)
                        }
                        self.refreshButtons()
                        
                    })
                 
                }else{
                    SWUtils.RunOnMainThread({ () -> Void in
                        HYBProgressHUD.showError("您的清单上传失败，请重新上传！")
                    })
                }
                
                return nil
            })
        }else{
            let token = ABQiniuUtils.uploadTokenOfFile(nil) as String!
            print("token :\(token)")
            QNUploadManager.sharedManager().putFile(strHashPath!, key: nil, token: token, complete: {
                info ,key , resp in
                
                print("status code :\(info.statusCode)")
                if (info != nil) {
                    if info.statusCode == 200 {
                        //            var ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
                        let newResp = resp
                        
                        
                        if (newResp != nil) {
                            let respInfo :AnyObject =   (newResp as? NSDictionary)!
                            if let newvalue = respInfo.objectForKey("key") as! String!{
                                self.realkey = newvalue
                            }else{
                                self.realkey = nil
                            }
                            self.aryPhotos.addObject(imageToSave)
                            if self.realkey != nil && self.realkey?.length != 0{
                                self.aryPhotosURI.addObject(self.realkey!)
                            }
                            self.refreshButtons()
                            
                        }
                    }else{
                        HYBProgressHUD.showError("您的清单上传失败，请重新上传！")
                    }
                }
                
                }, option: nil)

        }
        vMarkTabBar.hidden = false
        btnHiddenMarkTabbar.hidden = false
        picker.dismissViewControllerAnimated(true, completion: (nil))
    }

    
    func imagePickerControllerDidCancel(picker:UIImagePickerController)    {
        vMarkTabBar.hidden = false
        btnHiddenMarkTabbar.hidden = false
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func refreshButtons(){
        //        imgvPhoto.image = aryPhotos[0] as! UIImage
        vPay.hidden = false
        vMarkTabBar.hidden = false
        vMark.hidden = false
        btnHidePusPay.hidden = false
        btnHiddenMarkTabbar.hidden = false
//        photoCount++
//        var imgv1 = vPay.viewWithTag(100) as! UIImageView
//        var imgv2 = vPay.viewWithTag(101) as! UIImageView
//        var imgv3 = vPay.viewWithTag(102) as! UIImageView
        let btnAdd = vPay.viewWithTag(1000) as! UIButton
        
        for i in 0 ..< 3{
            let imgv = vPay.viewWithTag(100+i) as! UIImageView
            let btn = vPay.viewWithTag(6666+i) as! UIButton
            
            if i < aryPhotos.count{
                btn.hidden = false
                imgv.hidden = false
                imgv.image = self.aryPhotos[i] as? UIImage
            }else{
                btn.hidden = true
                imgv.hidden = true
                imgv.image = nil

            }
            
        }
        if aryPhotos.count == 3{
//            imgv1.image = self.aryPhotos[0] as! UIImage
//            btnAdd.frame =  CGRectMake(140 + (CGFloat)(150*(photoCount)), 95, 140, 140)
            btnAdd.hidden = true
        }else {
            btnAdd.frame =  CGRectMake(15 + (CGFloat)(120*(aryPhotos.count)), 85, 105, 105)
            btnAdd.layer.cornerRadius = 10
            btnAdd.clipsToBounds = true
            btnAdd.hidden = false
            
        }
    }
    
    
    //MARK: - MHOrderDetailNotification Delegate
    func orderNotificationUpdated(order: NSDictionary?) {
        if let dict = order{
            let order_id = dict.objectForKey("order_id")?.intValue!
            for i in 0 ..< aryList.count{
                let oi = aryList[i].objectForKey("order_id")?.intValue!
                
                if order_id==oi{
                    aryList.replaceObjectAtIndex(i, withObject: dict)
                    break
                }
            }
            
            tvList.reloadData()
        }
    }
    
    func showSelectedView(dic: NSDictionary?) {
        vNotificationDetail.hidden = true
        self.createOrderDetailView()
        vAllOrders.OrdersInfo = dic
        //        vAllOrders.hidden = false
    }
    
    
    func thePreviousStepClick(number: NSNumber?){
        
        
        if self.aryList.count>0{
            
            if number != 0 {
                self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: ((Int)(number!) - 1), inSection: 0))
            }else{
                self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))
                
            }
            
        }else{
           
        }
    }
    func theNectStepClick(number:NSNumber?){
        if self.aryList.count>0{
            
            let index = (Int)(number!)
            
            if index >= aryList.count-1{
                self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: aryList.count-1, inSection: 0))
            }else{
                self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: ((Int)(number!) + 1), inSection: 0))
            }
            
        }else{
           
        }
    }
    
    func hideOrderDetailView(number:NSNumber?){
        vAllOrders.hidden = true
        vNotificationDetail.hidden = false
    }
    
    //  MARK: - SWImageView Delegate
    func swImageViewLoadFinished(imgv: SWImageView) {
        
    }
    
    
    //获取取车员列表
    func loadGetCarPersonListData(){
        autoreleasepool { () -> () in
            dCurrentPage = 1;
            
            let dict = SHDataProvider.getDealerPersonList(["dealer_id":SHDataProvider.getDealerID()])
            
            print(dict)
            
            let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
            
            SWUtils.RunOnMainThread({ () -> Void in
                if let personList = ary{
                    self.aryPersonList.removeAllObjects()
                    self.aryPersonList = NSMutableArray(array: personList)
                    
                    if personList.count>0{
                        //                        var formatter = NSDateFormatter()
                        //                        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
                        //                        var d = formatter.dateFromString(personList[0].objectForKey("create_time") as! String)
                        //                        if let dd = d{
                        //                            NSUserDefaults.standardUserDefaults().setObject(dd, forKey: "LatestOrderTime")
                        //                        }
                    }
                }else{
                    self.aryPersonList.removeAllObjects()
                }
                
                self.tvListPerson.reloadData()
                
            })
        }
    }
    
    
    
    //选取取车员
    func selectedGetCarPerson(){
        autoreleasepool { () -> () in
            
            //            let getCarID = vAllOrders.allOrdersInfo?.objectForKey("get_car_id")
            let work_no = dicSelectedPersonInfo!.objectForKey("work_no")
            let order_id = vAllOrders.OrdersInfo?.objectForKey("order_id")
            let dict = SHDataProvider.shopSelectedGetCarPerson(["work_no":work_no!,"order_id":order_id!])
            
            SWUtils.RunOnMainThread({ () -> Void in
                let code = (dict!.objectForKey("code") as! NSNumber).integerValue
                NSLog("response code:%d",code)
                
                if code == 200 {
                    UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                    let mut = NSMutableDictionary(dictionary: self.vAllOrders.OrdersInfo!) as NSMutableDictionary
                    mut.setObject("6", forKey: "order_status")
                    
//                    self.vAllOrders.OrdersInfo = NSDictionary(dictionary: mut)
                    self.vAllOrders.OrdersInfo = NSDictionary(dictionary: (dict?.objectForKey("data"))! as! [NSObject : AnyObject])
                    
                }else{
                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                }
                
                self.allOrdesUpdated(self.vAllOrders.OrdersInfo)
                
            })
        }
    }
    
    //选取送车员
    func selectedSendCarPerson(){
        autoreleasepool { () -> () in
            
            let sendCarID = vAllOrders.OrdersInfo?.objectForKey("send_car_id")
            let work_no = dicSelectedPersonInfo!.objectForKey("work_no")
            let order_id = vAllOrders.OrdersInfo?.objectForKey("order_id")
            
            let dict = SHDataProvider.shopSelectedSendCarPerson(["order_id":order_id!,"work_no":work_no!])
            //            var ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
            
            SWUtils.RunOnMainThread({ () -> Void in
                let code = (dict!.objectForKey("code") as! NSNumber).integerValue
                NSLog("response code:%d",code)
                
                if code == 200 {
                    UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                    let mut = NSMutableDictionary(dictionary: self.vAllOrders.OrdersInfo!) as NSMutableDictionary
                    mut.setObject("11", forKey: "order_status")
                    
//                    self.vAllOrders.OrdersInfo = NSDictionary(dictionary: mut)
                    self.vAllOrders.OrdersInfo = NSDictionary(dictionary: (dict?.objectForKey("data"))! as! [NSObject : AnyObject])
                    
                }else{
                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                }
                
                self.allOrdesUpdated(self.vAllOrders.OrdersInfo)
                
                
            })
        }
    }
    
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        if string == "0" || string == "1" || string == "2" || string == "3" || string == "4" || string == "5" || string == "6" || string == "7" || string == "8" || string == "9" || string == "" || string == "." {
            let aString :NSString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
            let arr = aString.componentsSeparatedByString(".")
            if arr.count>2 {
                textField.text = aString.substringToIndex(aString.length - 1)
                return false
            }else if arr.count <= 2 {
                
                return true
            }
            
            return true
        }
        
        return false
        
    }
    
    func getScanNumber(str: NSString) {
        searchBar.text = str as String
        self.refresh()
    }
    
    func keyboardWillHide(notification:NSNotification){
        //
        let info = notification.userInfo as! NSDictionary
        if info.objectForKey(UIKeyboardAnimationDurationUserInfoKey) != nil{
            btnResignSearchBar.hidden = true
            searchBar.resignFirstResponder()
        }
        
        
    }
    
    func networkStatusChanged(notification: NSNotification) {
        let userInfo = notification.userInfo as! AnyObject
        print(userInfo)
//        let status1 = userInfo.objectForKey("Status")
        let status = Reach().connectionStatus()
        switch status {
        case .Unknown, .Offline:
            print("Not connected")
            if networkConnectFalse == false{
               let alert:UIAlertView = UIAlertView(title: "网络连接失败", message: "请查看您的网络设置", delegate: self, cancelButtonTitle: "确定")
               alert.tag = 10000
                alert.show()
               networkConnectFalse = true
            }
            case .Online(.WWAN):
            print("Connected via WWAN")
        case .Online(.WiFi):
            print("Connected via WiFi")
        }
    }
    
    func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
        if alertView.tag == 10000{
            networkConnectFalse = false
        }else if alertView.tag == 10001{
            BoolGetMore = false
        }
    }
    
    func initOSSCliect(){
        let credential:OSSCredentialProvider = OSSFederationCredentialProvider.init(federationTokenGetter: {
            Void in
            
             let dealer_uid = SHDataProvider.getUserInfo()?.objectForKey("uid") as! String
             let dict = SHDataProvider.getCredentials(["uid":dealer_uid])
            let code = (dict!.objectForKey("code") as! NSNumber).integerValue
            if code == 200 {
                let token = OSSFederationToken.init()
                token.tAccessKey = dict?.objectForKey("data")?.objectForKey("AccessKeyId") as! String
                token.tSecretKey = dict?.objectForKey("data")?.objectForKey("AccessKeySecret") as! String
                token.tToken = dict?.objectForKey("data")?.objectForKey("SecurityToken") as! String
                token.expirationTimeInGMTFormat = dict?.objectForKey("data")?.objectForKey("Expiration") as! String
                
                return token
                
             }
            return nil
        })
        
        let conf = OSSClientConfiguration.init()
        conf.maxRetryCount = 2
        conf.timeoutIntervalForRequest = 30
        conf.timeoutIntervalForResource = 24*60*60
        
        client = OSSClient.init(endpoint: OSSEndPoint, credentialProvider: credential, clientConfiguration: conf)
    }
    
//    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
////        var touch = (touches as NSSet).anyObject()
//        var tch = ((event?.allTouches())! as NSSet).anyObject()
//        if (searchBar.isFirstResponder() && tch?.view != searchBar) || tch?.view == tvList || tch?.view == vAllOrders{
//            searchBar.resignFirstResponder()
//        }
//    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
